package org.mfoyou.agent.center.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.fastjson.JSON;
import org.mfoyou.agent.center.dao.inf.HuawuServiceCouponMapper;
import org.mfoyou.agent.center.dao.inf.HuawuServiceCouponRuleMapper;
import org.mfoyou.agent.center.dao.inf.HuawuServiceUserCouponMapper;
import org.mfoyou.agent.center.dao.inf.HuawuSystemMapper;
import org.mfoyou.agent.common.dao.domain.*;
import org.mfoyou.agent.common.dao.domain.HuawuServiceCouponExample.Criteria;
import org.mfoyou.agent.common.inf.IOther;
import org.mfoyou.agent.utils.common.ArrayListObject;
import org.mfoyou.agent.utils.sql.MybatisGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * OhterService
 *
 * @author hzhang7
 */
@Service
public class OtherService implements IOther {

    private static final Logger logger = LoggerFactory.getLogger(OtherService.class);

    @Autowired
    HuawuServiceCouponMapper huawuServiceCouponMapper;

    @Autowired
    HuawuSystemMapper huawuSystemMapper;

    @Autowired
    HuawuServiceUserCouponMapper huawuServiceUserCouponMapper;

    @Autowired
    HuawuServiceCouponRuleMapper huawuServiceCouponRuleMapper;

    @Override
    public int addServiceCoupon(HuawuServiceCoupon huawuServiceCoupon) {
        return huawuServiceCouponMapper.insertSelective(huawuServiceCoupon);
    }

    @Override
    public int modifyCoupon(HuawuServiceCoupon huawuServiceCoupon, HuawuServiceCoupon huawuServiceCouponEx) {
        HuawuServiceCouponExample huawuServiceCouponExample = new HuawuServiceCouponExample();
        MybatisGenerator.makeExample(huawuServiceCouponEx, huawuServiceCouponExample.or());
        return huawuServiceCouponMapper.updateByExampleSelective(huawuServiceCoupon, huawuServiceCouponExample);
    }

    @Override
    public ArrayListObject<HuawuServiceCoupon> getCouponList(Integer agentId, Integer pageId, Integer pageSize, Integer couponId, Integer state) {
        // 构造查询参数对象
        HuawuServiceCouponExample huawuServiceCouponExample = new HuawuServiceCouponExample();
        Criteria andAgentIdEqualTo = huawuServiceCouponExample.or().andAgentIdEqualTo(agentId);
        if (couponId != null) {
            andAgentIdEqualTo.andServiceCouponIdEqualTo(couponId);
        }
        if (state != null) {
            if (state == 0) {
                andAgentIdEqualTo.andCouponEndTimeGreaterThan(new Date()).andCouponStateEqualTo(1);
            }
            if (state.intValue() == 1) {
                andAgentIdEqualTo.andCouponEndTimeLessThan(new Date());
            }
        }

        // 查询总条数
        int count = huawuServiceCouponMapper.countByExample(huawuServiceCouponExample);
        MybatisGenerator.setLimit(huawuServiceCouponExample, pageId, pageSize);
        huawuServiceCouponExample.setOrderByClause(" service_coupon_id desc");

        // 分页查询列表
        List<HuawuServiceCoupon> selectByExample = huawuServiceCouponMapper.selectByExample(huawuServiceCouponExample);
        for (HuawuServiceCoupon huawuServiceCoupon : selectByExample) {
            //优化建议： 使用的时候增加 不用SQL查询
            String sql = "select ifnull(count(*),0) coun from huawu_service_user_coupon where coupon_id = " + huawuServiceCoupon.getServiceCouponId() + " and touch_state = 0";
            int useCount = Integer.parseInt(huawuSystemMapper.select_item(sql).get("coun").toString());
            // 外键查询有多少优惠券已经被使用
            huawuServiceCoupon.setCouponUsed(useCount);
        }
        return ArrayListObject.bliudArrayList(selectByExample, pageId, pageSize, count);
    }

    @Override
    public List<HuawuServiceCoupon> getAgentCouponListByUser(Integer agentId, Integer userId) {
        // 构造查询参数
        HuawuServiceCouponExample huawuServiceCouponExample = new HuawuServiceCouponExample();
        huawuServiceCouponExample.or().andAgentIdEqualTo(agentId).andCouponCountGrterThanSold()
                .andCouponStartTimeLessThan(new Date()).andCouponEndTimeGreaterThan(new Date())
                .andCouponStateEqualTo(1);

        // 查询列表
        List<HuawuServiceCoupon> coupons = huawuServiceCouponMapper.selectByExample(huawuServiceCouponExample);
        if (userId == null)
            return coupons;

        for (HuawuServiceCoupon huawuServiceCoupon : coupons) {
            // 构造查询参数
            HuawuServiceUserCouponExample huawuServiceUserCouponExample = new HuawuServiceUserCouponExample();
            huawuServiceUserCouponExample.or().andUserIdEqualTo(userId).andCouponIdEqualTo(huawuServiceCoupon.getServiceCouponId());
            if (huawuServiceUserCouponMapper.countByExample(huawuServiceUserCouponExample) > 0) {
                // 设置优惠券状态为 5?
                huawuServiceCoupon.setCouponState(5);
            }
        }
        return coupons.stream().filter(huawuServiceCoupon -> huawuServiceCoupon.getCouponState() != 5)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public List<Integer> takeCoupons(Integer[] couponIds, Integer userid) {
        synchronized (this.getClass()) {
            List<Integer> ret = new ArrayList<>();
            for (Integer coupId : couponIds) {
                HuawuServiceUserCouponExample huawuServiceUserCouponExample = new HuawuServiceUserCouponExample();
                huawuServiceUserCouponExample.or().andUserIdEqualTo(userid).andCouponIdEqualTo(coupId);
                int countByExample = huawuServiceUserCouponMapper.countByExample(huawuServiceUserCouponExample);
                if (countByExample == 0) {
                    int checkCouponCount = huawuServiceUserCouponMapper.checkCouponCount(coupId, 1);
                    if (checkCouponCount == 0)
                        continue;
                    HuawuServiceUserCoupon huawuServiceUserCoupon = new HuawuServiceUserCoupon();
                    huawuServiceUserCoupon.setCouponId(coupId);
                    huawuServiceUserCoupon.setUserId(userid);
                    huawuServiceUserCouponMapper.insertSelective(huawuServiceUserCoupon);
                    ret.add(coupId);
                }
            }
            return ret;
        }
    }

    @Override
    public List<Map<String, Object>> getUserCouponList(Integer userId, Integer state, Integer type) {
        String sql = "select coupon_text couponText,use_type useType,reduceValue,coupon_name couponName,"
                + "coupon_start_time couponStartTime,coupon_end_time couponEndTime,touch_id touchId,touch_state touchState from "
                + "huawu_service_coupon  a inner join   (select coupon_id  service_coupon_id,touch_state,touch_id "
                + " from huawu_service_user_coupon where ";
        if (state != null) {
            sql += "touch_state = " + state + " and ";
        }
        sql += "user_id = " + userId + " ) b using(service_coupon_id) order by touch_state desc,service_coupon_id desc";
        List<Map<String, Object>> select_list = huawuSystemMapper.select_list(sql);
        return select_list;
    }

    @Override
    public HuawuServiceCoupon getCouponByTouchId(Integer touchId, Integer agentId) {
        HuawuServiceUserCoupon selectByPrimaryKey = huawuServiceUserCouponMapper.selectByPrimaryKey(touchId);
        if (selectByPrimaryKey.getTouchState() == 0) {
            return null;
        }
        HuawuServiceCouponExample huawuServiceCouponExample = new HuawuServiceCouponExample();
        huawuServiceCouponExample.or().andAgentIdEqualTo(agentId).andServiceCouponIdEqualTo(selectByPrimaryKey.getCouponId())
                .andCouponStartTimeLessThan(new Date()).andCouponEndTimeGreaterThan(new Date());
        return MybatisGenerator.getOneValue(huawuServiceCouponMapper.selectByExample(huawuServiceCouponExample));
    }

    @Override
    public List<HuawuServiceCoupon> getCanUseCoupon(Integer agentId, Integer userId) {
        logger.info(String.format("查询可用优惠券: agentId=[%s];userId=[%s]", agentId, userId));
        HuawuServiceUserCouponExample huawuServiceUserCouponExample = new HuawuServiceUserCouponExample();
        huawuServiceUserCouponExample.or().andTouchStateEqualTo(1).andUserIdEqualTo(userId);
        List<HuawuServiceUserCoupon> selectByExample = huawuServiceUserCouponMapper.selectByExample(huawuServiceUserCouponExample);
        logger.info(String.format("huawu_service_user_coupon list=[%s]", JSON.toJSONString(selectByExample)));

        if (selectByExample.size() == 0) {
            return new ArrayList<>();
        }

        Map<Integer, Integer> collect = selectByExample.stream().collect(Collectors.toMap(HuawuServiceUserCoupon::getCouponId, HuawuServiceUserCoupon::getTouchId));
        logger.info(String.format("userCoupon 集合转换为 Map=[%s]", JSON.toJSONString(collect)));

        HuawuServiceCouponExample huawuServiceCouponExample = new HuawuServiceCouponExample();
        huawuServiceCouponExample.or().andAgentIdEqualTo(agentId).andServiceCouponIdIn(new ArrayList<>(collect.keySet())).andCouponStartTimeLessThan(new Date()).andCouponEndTimeGreaterThan(new Date());
        List<HuawuServiceCoupon> coupons = huawuServiceCouponMapper.selectByExample(huawuServiceCouponExample);
        logger.info(String.format("huawu_service_coupon list=[%s]", JSON.toJSONString(coupons)));

        coupons.stream().forEach(huawuServiceCoupon -> huawuServiceCoupon.setTouchId(collect.get(huawuServiceCoupon.getServiceCouponId())));
        logger.info(String.format("最终转换得到返回的优惠券列表 coupons=[%s]", JSON.toJSONString(coupons)));

        return coupons;
    }

    @Override
    public int updateCoupon(HuawuServiceUserCoupon huawuServiceUserCoupon) {
        return huawuServiceUserCouponMapper.updateByPrimaryKeySelective(huawuServiceUserCoupon);
    }

    @Override
    public int saveServiceCouponRule(HuawuServiceCouponRule rule) {
        int result;
        if (rule.getId() != null) {
            rule.setModifyTime(new Date());
            result = huawuServiceCouponRuleMapper.updateRuleById(rule);
        } else {
            result = huawuServiceCouponRuleMapper.insert(rule);
        }
        return result;
    }

    @Override
    public HuawuServiceCouponRule getServiceCouponRule() {
        HuawuServiceCouponRule rule = huawuServiceCouponRuleMapper.selectRule();
        return rule;
    }
}
